package service

import (
	"encoding/base64"
	systemConfig "gin-worked/app/system/config"
	"gin-worked/app/system/model"
	"gin-worked/config"
	"strconv"
	"time"
)

// UserApi 用户数据返回结构体
type UserApi struct {
	Id       int
	Nickname string
	Tel      string
	Headimg  string
}

type UserListApi struct {
	Total int
	List  interface{}
}

// LoginApi 登录返回的结构体
type LoginApi struct {
	Token string
}

// Login 登录
func Login(username string, password string) Res {

	data := &model.System{
		Username: username,
	}

	info, err := model.GetSystemInfo(data)

	if err != nil {
		return Res{0, err, ""}
	}

	passwordEd := []byte(password)
	//

	key := []byte(info.Salt)
	key = config.PadToBlockSize(key)

	encrypt, err := config.Encrypt(passwordEd, key)

	if err != nil {
		return Res{0, err, ""}
	}

	pwd := base64.StdEncoding.EncodeToString(encrypt) //

	if pwd != info.Password {
		return Res{0, "密码不正确，请重新输入", ""}
	}

	if info.Status != "1" {
		return Res{0, "该账号已被禁止", ""}
	}

	getToken, _ := config.Rdb.Get(config.Rctx, "user:"+strconv.Itoa(info.Id)).Result() // 查看用户token 是否登录过期 没有过期直接返回

	if getToken != "" {
		loginEd := LoginApi{
			Token: getToken,
		}
		return Res{200, "success", loginEd}
	}

	token, err1 := systemConfig.CreateToken(info.Id, info.Nickname, info.Tel, info.Headimg)

	if err1 != nil {
		return Res{0, err, ""}
	}

	login := LoginApi{
		Token: token,
	}
	expireTime := systemConfig.GetExpireTime()

	errors := config.Rdb.Set(config.Rctx, token, token, expireTime).Err() //缓存用户token
	if errors != nil {
		return Res{Code: 0, Msg: errors, Data: ""}
	}

	_ = config.Rdb.Set(config.Rctx, "user:"+strconv.Itoa(info.Id), token, expireTime).Err() // 缓存用户token 用于更新

	return Res{1, "success", login}
}

// GetSystemInfo 获取详情
func GetSystemInfo(uid string) Res {
	id, _ := strconv.Atoi(uid)
	data := &model.System{
		Id: id,
	}

	info, err := model.GetSystemInfo(data)

	if err != nil {
		return Res{Code: 0, Msg: err, Data: ""}
	}

	dataEd := UserApi{
		Id:       info.Id,
		Nickname: info.Nickname,
		Tel:      info.Tel,
		Headimg:  info.Headimg,
	}

	return Res{Code: 1, Msg: "success", Data: dataEd}
}

// SystemAdd 添加后台管理员账号
func SystemAdd(username string, nickname string, tel string, headimg string, password string) Res {
	slat := systemConfig.Random(4)

	key := []byte(slat)
	key = config.PadToBlockSize(key)
	pwd, err := config.Encrypt([]byte(password), key)

	where := &model.System{
		Username:   username,
		Status:     strconv.Itoa(1),
		DeleteTime: strconv.Itoa(0),
	}
	info, _ := model.GetSystemInfo(where)

	if info.Id > 0 {
		return Res{0, "该账户已存在", ""}
	}

	if err != nil {
		return Res{0, err, ""}
	}
	times := time.Now().Unix()

	data := &model.System{
		Username:   username,
		Nickname:   nickname,
		Tel:        tel,
		Headimg:    headimg,
		Status:     strconv.Itoa(1),
		DeleteTime: strconv.Itoa(0),
		Password:   base64.StdEncoding.EncodeToString(pwd),
		Salt:       slat,
		CreateTime: strconv.FormatInt(times, 10),
		UpdateTime: strconv.FormatInt(times, 10),
	}

	id, errorEd := model.SystemAdd(data)

	if errorEd != nil {
		return Res{0, errorEd, ""}
	}
	ataEd := UserApi{
		Id: id,
	}
	return Res{1, "success", ataEd}

}

// SystemList 获取全部管理人员
func SystemList(offset string, limit string) Res {
	data := &model.System{
		Status:     strconv.Itoa(1),
		DeleteTime: strconv.Itoa(0),
	}
	offsets, _ := strconv.Atoi(offset)
	limits, _ := strconv.Atoi(limit)
	total := model.SystemTotal(data)
	field := []string{"id", "username", "nickname", "headimg", "tel", "status"} //查询字段
	list, err := model.SystemList(data, field, "create_time DESC", offsets, limits)

	if err != nil {
		return Res{0, err, ""}
	}
	dataEd := UserListApi{
		Total: int(total),
		List:  list,
	}
	return Res{1, "success", dataEd}
}

// SystemEdit 后台管理人员信息编辑
func SystemEdit(id string, nickname string, tel string, headimg string) Res {
	ids, _ := strconv.Atoi(id)
	data := &model.System{
		Id: ids,
	}
	var content = map[string]interface{}{"nickname": nickname, "tel": tel, "headimg": headimg}
	err := model.SystemEdit(data, content)
	if err != nil {
		return Res{0, err, ""}
	}

	return Res{1, "success", ""}
}

// SystemEditPwd SystemEdit 后台管理人员信息编辑
func SystemEditPwd(id string, password string) Res {

	salt := systemConfig.Random(4) //重新更新密码盐

	key := []byte(salt)
	key = config.PadToBlockSize(key)

	encrypt, err := config.Encrypt([]byte(password), key)

	if err != nil {
		return Res{0, err, ""}
	}

	pwd := base64.StdEncoding.EncodeToString(encrypt) //

	ids, _ := strconv.Atoi(id)

	data := &model.System{
		Id: ids,
	}
	var content = map[string]interface{}{"password": pwd, "salt": salt}
	err1 := model.SystemEdit(data, content)
	if err1 != nil {
		return Res{0, err1, ""}
	}
	getToken, _ := config.Rdb.Get(config.Rctx, "user:"+id).Result() // 查看用户token 是否登录过期 没有过期直接返回

	_ = config.Rdb.Del(config.Rctx, "user:"+id).Err()
	_ = config.Rdb.Del(config.Rctx, getToken).Err()
	return Res{1, "success", ""}
}

func SystemEditStatus(id string, status string) Res {

	ids, _ := strconv.Atoi(id)

	data := &model.System{
		Id: ids,
	}
	status1, _ := strconv.Atoi(status)
	var content = map[string]interface{}{"status": status1}
	err1 := model.SystemEdit(data, content)
	if err1 != nil {
		return Res{0, err1, ""}
	}

	return Res{1, "success", ""}
}

func SystemEditHeadImg(id string, headimg string) Res {

	ids, _ := strconv.Atoi(id)

	data := &model.System{
		Id: ids,
	}

	var content = map[string]interface{}{"headimg": headimg}
	err1 := model.SystemEdit(data, content)
	if err1 != nil {
		return Res{0, err1, ""}
	}

	return Res{1, "success", ""}
}
